//
//  HWHomeRecommendController.swift
//  HWanGame
//
//  Created by 王昌健 on 2021/12/23.
//  Copyright © 2021 94Wan. All rights reserved.
//

import UIKit
import JXSegmentedView
class HWHomeRecommendController: HWBaseViewController {
    var tableView:UITableView!
    var tableViewProtocol = HWHomeRecommendProtocol()
    var httpManager = HWHomeHttpManager()
    var type = "-1"
    var playerView:CLPlayerView!
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initUI()
        
        initFrame()
        
//        loadData()
        
        addRefresh()
        
        addAction()
        
        // 检查网络连接
        checkNetwork()
        
    }
    
    // 检查网络连接
    func checkNetwork() {
        let monitor = NWPathMonitor()
        
        monitor.pathUpdateHandler = { [weak self] path in
            DispatchQueue.main.async {
                if path.status == .satisfied {
                    print("网络已连接")
                } else {
                    //询问用户是否前往设置中开启网络
                    let alertController = UIAlertController(title: "网络错误", message: "请授予应用程序网络权限", preferredStyle: .alert)
                    let settingsAction = UIAlertAction(title: "设置", style: .default) { (_) -> Void in
                        guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else {
                            return
                        }
                        
                        if UIApplication.shared.canOpenURL(settingsUrl) {
                            UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
                                print("设置打开: \(success)")
                            })
                        }
                    }
                    
                    let cancelAction = UIAlertAction(title: "取消", style: .default, handler: nil)
                    alertController.addAction(cancelAction)
                    alertController.addAction(settingsAction)
                    self?.present(alertController, animated: true, completion: nil)
                }
            }
        }
        
        let queue = DispatchQueue(label: "Monitor")
        monitor.start(queue: queue)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if self.playerView != nil {
            self.playerView.destroyPlayer()
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        loadData()
    }
    
}

extension HWHomeRecommendController {
    private func initUI() -> Void {
        navigationView.isHidden = true
        view.backgroundColor = .clear
        
        tableView = UITableView.init(frame: CGRect.zero, style: UITableView.Style.plain)
        tableView.delegate = tableViewProtocol
        tableView.dataSource = tableViewProtocol
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        tableView.rowHeight = UITableView.automaticDimension
        tableView.estimatedRowHeight = 40
        tableView.estimatedSectionHeaderHeight = 0
        tableView.estimatedSectionFooterHeight = 0
        tableView.showsVerticalScrollIndicator = false
        tableView.autoresizingMask = [.flexibleHeight,.flexibleWidth]
        view.addSubview(tableView)
        tableView.contentInsetAdjustmentBehavior = .never
        if #available(iOS 15.0, *) {
            self.tableView.sectionHeaderTopPadding = 0
        } else {
            // Fallback on earlier versions
        }
        //        let playback = zfplayer
        //
        //        let zfPlayer = ZFPlayerController.init(scrollView: tableView, playerManager: <#T##ZFPlayerMediaPlayback#>, containerViewTag: <#T##Int#>)
    }
    
    private func initFrame() -> Void {
        tableView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.bottom.equalToSuperview()
            
        }
    }
}

extension HWHomeRecommendController:JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }
}

extension HWHomeRecommendController {
    func loadData() -> Void {
        httpManager.getHomeInfo(type: self.type) { model in
            self.tableView.mj_header?.endRefreshing()
            self.tableViewProtocol.model = model
            self.tableView.reloadData()
        } failure: { error in
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
        }
        
    }
    
    func addRefresh() -> () {
        
        tableView.mj_header = MJRefreshNormalHeader()
        tableView.mj_header?.setRefreshingTarget(self, refreshingAction: #selector(self.loadNewData))
    }
    
    
    @objc func loadNewData() -> () {
        loadData()
    }
    
}

extension HWHomeRecommendController {
    func addAction() -> Void {
        self.tableViewProtocol.didClickGame = {
            gameId in
            let gameDetail = HWGameDetailController()
            gameDetail.gameId = gameId
            self.navigationController?.pushViewController(gameDetail, animated: true)
        }
        
        self.tableViewProtocol.didClickItem = {
            mod in
            if mod.login == "1" {
                if HWLocallyStoredData.getLoginUserID().count>0{
                    if mod.type == "0" && mod.name == "更多福利" {
                        (HWUniversal.getCurrentVc().tabBarController as! HWTabBarController1).selectedIndex = 3
                    } else {
                        self.jumpTo(type: mod.type,urlString: mod.url)
                    }
                }else{
                    let loginController = HWLoginController()
                    self.navigationController?.pushViewController(loginController, animated: true)
                }
            }else {
                if mod.type == "0" && mod.name == "更多福利" {
                    (HWUniversal.getCurrentVc().tabBarController as! HWTabBarController1).selectedIndex = 3
                } else {
                    self.jumpTo(type: mod.type,urlString: mod.url)
                }
            }
        }
        
        self.tableViewProtocol.didClickHeavyItem = {
            mod in
//            if mod.style == "0" {
                let gameDetail = HWGameDetailController()
                gameDetail.gameId = mod.id
                self.navigationController?.pushViewController(gameDetail, animated: true)
//            }else {
//
//            }
        }
        
        self.tableViewProtocol.didClickSaveCardItem = {
            mod in
            if HWLocallyStoredData.getLoginUserID().count>0{
                HWUniversal.pushController(type: mod.type, urlString: mod.url)
            }else{
                let loginController = HWLoginController()
                self.navigationController?.pushViewController(loginController, animated: true)
            }
            
        }
        
        self.tableViewProtocol.gameImageViewClick = {
            imageView ,model in
            if model.video.count > 0 {
                self.playerView = CLPlayerView.init(frame: imageView.frame)
                self.playerView.frame = imageView.frame
                self.playerView.update { config in
                    config?.topToolBarHiddenType = .small
                    config?.videoFillMode = .resizeAspect
                    config?.autoRotate = false
                }
                self.playerView.url = URL(string: model.video)
                imageView.addSubview(self.playerView)
                self.playerView.playVideo()
                self.playerView.endPlay {
                    if self.playerView != nil {
                        self.playerView.destroyPlayer()
                    }
                }
                self.playerView.snp.makeConstraints { make in
                    make.edges.equalToSuperview()
                }
            }else{
                let gameDetail = HWGameDetailController()
                gameDetail.gameId = model.id
                self.navigationController?.pushViewController(gameDetail, animated: true)
            }
            
            
        }
        
        self.tableViewProtocol.clickTagView = {
            name,id in
            let detailController = HWbiaoqiankongzhiViewController()
            detailController.dataDic = ["name":name,"id":id]
            self.navigationController?.pushViewController(detailController, animated: true)
        }
        
        self.tableViewProtocol.moreButtonClick = {
            (HWUniversal.getCurrentVc().tabBarController as! HWTabBarController1).selectedIndex = 1
        }
        
        self.tableViewProtocol.endPlay = {
            if self.playerView != nil {
                self.playerView.destroyPlayer()
            }
        }
    }
    
    func jumpTo(type:String,urlString:String) -> Void {
        HWUniversal.pushController(type: type, urlString: urlString)
    }
}
